package cn.com.libertymutual.core.security.jwt;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.TbSpUser;

@RestController("jwtAuthenticationTokenController")
@RequestMapping("/nol/token")
public class JwtAuthenticationTokenController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private RedisUtils redis;
    
	@RequestMapping(value="login", method=RequestMethod.POST)
    public ServiceResult createAuthenticationToken( String username, String password, @RequestAttribute(DeviceUtils.CURRENT_DEVICE_ATTRIBUTE) Device device) {

		ServiceResult sr = new ServiceResult();
		
		// Perform the security
	    /*final Authentication authentication = authenticationManager.authenticate(
	            new UsernamePasswordAuthenticationToken(
	                    authenticationRequest.getUsername(),
	                    authenticationRequest.getPassword()
	            )
	    );
	    SecurityContextHolder.getContext().setAuthentication(authentication);*/

		redis.set("KYB", "bob.Kuang");
	    List<TbSpUser> userList = Lists.newArrayList();///userDao.findByWxOpenId(username);
	    
	    System.out.println(redis.get("KYB"));

	    System.out.println(redis.get("USER_CODE_SEQ"));
	    
	    TbSpUser user = new TbSpUser();
	    user.setId(1009);
	    user.setUserCode("WX00000002");
	    user.setUserName("况尤波"+username);
	    userList.add(user);
	    if( userList == null || userList.size() < 1 ) {
	    	sr.setAppFail(username);
	    	return sr;
	    }
	    
	    
	    // Reload password post-security so we can generate token
	    final UserDetails userDetails = JwtUserFactory.create(userList.get(0));
	    final String token = jwtTokenUtil.generateToken(userDetails, device);

	    // Return the token
	    sr.setToken(token);
	    
	    return sr;
    }
	
	@RequestMapping(value = "refresh", method = RequestMethod.GET)
    public ServiceResult refreshAndGetAuthenticationToken(HttpServletRequest request) {
		ServiceResult sr = new ServiceResult();
		
        String token = request.getHeader(tokenHeader);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        TbSpUser user = null;///userDao.findByUserCode(username);

        if (jwtTokenUtil.canTokenBeRefreshed(token)) {
            sr.setToken( jwtTokenUtil.refreshToken(token) );
        } else {
            sr.setAppFail("refresh fail");
        }
        
        return sr;
    }
}
